//
//  AppDelegate.swift
//  LVWeibo
//
//  Created by lv on 15/6/23.
//  Copyright © 2015年 lv. All rights reserved.
//

import UIKit
import AFNetworking

/// 全局变量记录账户信息(下次就不用在磁盘中加载)
var sharedUserAccount = UserAccount.loadAccount()

/// 切换根控制器通知
var WBSwitchMainInterfaceNotification = "WBSwitchMainInterfaceNotification"

/// @UIApplicationMain 是表示程序的入口，swift 中没有 main.m
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        // 打印归档保存的用户信息
        print(sharedUserAccount)
        
        // 设置网络指示
        setupNetWork()
        
        // 设置外观，一经设置全局有效
        setupAppearance()
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        window?.rootViewController = defaultController()
        window?.makeKeyAndVisible()
        
        // 注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchRootViewController:", name: WBSwitchMainInterfaceNotification, object: nil)
    
        return true
    }
    
    //MARK:- 切换根控制器
    // 注意：此方法不能设置为私有的!
    func switchRootViewController(n:NSNotification) {
        //  判断 object 是否为 true，如果是，显示 MainViewController
        let isMainVc = n.object as! Bool
        window?.rootViewController = isMainVc ? MainViewController() : WelcomeViewController()
    }
    
    //MARK:- 默认控制器
    private func defaultController() -> UIViewController {
        // 1.判断用户是否登录
        if sharedUserAccount != nil {
            // 判断是否版本更新
            return isNewUpdate() ? NewFeatureViewController() : WelcomeViewController()
        }
        // 2.用户没登陆，显示访客视图
        return MainViewController()
    }
    
    
    //MARK:- 检查版本是否更新
    private func isNewUpdate() -> Bool {
        // 1.获取当前版本信息,将字符串转换为double类型
        let currentVersion = Double(NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String)

        // 2.获取沙盒中版本信息
        let version = "versionKey"
        let sandBoxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(version)
        
        // 3.将版本信息写入沙盒
        if currentVersion > sandBoxVersion {
            NSUserDefaults.standardUserDefaults().setDouble(currentVersion!, forKey: version)
            return true
        }
        return false
    }
    
    //MARK:- 设置网络
    private func setupNetWork() {
        // 设置网络指示器
        AFNetworkActivityIndicatorManager.sharedManager().enabled = true
        // 设置网络缓存
        let urlCache = NSURLCache(memoryCapacity: 4 * 1024 * 1024, diskCapacity: 20 * 1024 * 1024, diskPath: nil)
        NSURLCache.setSharedURLCache(urlCache)
    }
    //MARK:- 设置外观
    private func setupAppearance() {
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = UIColor.orangeColor()
    }
}

